In this course, I will learn how to use R for statistical analysis.
My GitHub repository: https://github.com/jsimola/IODS-project
Read the data
rm(list = ls()) # clear workspace first
learning2014 <- read.csv("~/Documents/GitHub/IODS-project/learning2014.csv") # my own data wrangling
# read.table("~/Documents/GitHub/IODS-project/data/learning2014.txt", sep = ",") # Kimmo's data
Explore the structure and dimensions of the dataset
str(learning2014)
## 'data.frame': 166 obs. of 7 variables:
## $ gender : Factor w/ 2 levels "F","M": 1 2 1 2 2 1 2 1 2 1 ...
## $ Age : int 53 55 49 53 49 38 50 37 37 42 ...
## $ Attitude: int 37 31 25 35 37 38 35 29 38 21 ...
## $ deep : num 3.58 2.92 3.5 3.5 3.67 ...
## $ stra : num 3.38 2.75 3.62 3.12 3.62 ...
## $ surf : num 2.58 3.17 2.25 2.25 2.83 ...
## $ Points : int 25 12 24 10 22 21 21 31 24 26 ...
dim(learning2014)
## [1] 166 7
The data includes 7 variables and 166 observations. The variables are: 1. Gender (Female = 1 Male = 2) 2. Age 3. Attitude 4-6. Mean scores of the deep, strategic and surface learning 7. Exam points
library(ggplot2) # Access the gglot2 library
Show a graphical overview of the data
# show gender distributions as bar graph
p1 <- ggplot(learning2014, aes(gender))
p1 + geom_bar()
# display variable distributions as histogram
p2 <- ggplot(learning2014, aes(Age))
p2 + geom_histogram(binwidth = 5)
p3 <- ggplot(learning2014, aes(Attitude))
p3 + geom_histogram(binwidth = 2)
p4 <- ggplot(learning2014, aes(deep))
p4 + geom_histogram(binwidth = 0.5)
p5 <- ggplot(learning2014, aes(stra))
p5 + geom_histogram(binwidth = 0.5)
p6 <- ggplot(learning2014, aes(surf))
p6 + geom_histogram(binwidth = 0.5)
p7 <- ggplot(learning2014, aes(Points))
p7 + geom_histogram(binwidth = 2)
# show relationships between variables
p8 <- ggplot(learning2014, aes(x = Attitude, y = Points, col=gender))
p8 + geom_point() + ggtitle("Relationship between exam points and deep learning") + geom_smooth(method = "lm")
p9 <- ggplot(learning2014, aes(x = deep, y = Points, col=gender))
p9 + geom_point() + ggtitle("Relationship between exam points and deep learning") + geom_smooth(method = "lm")
p10 <- ggplot(learning2014, aes(x = stra, y = Points, col=gender))
p10 + geom_point() + ggtitle("Relationship between exam points and strategic learning") + geom_smooth(method = "lm")
p11 <- ggplot(learning2014, aes(x = surf, y = Points, col=gender))
p11 + geom_point() + ggtitle("Relationship between exam points and surface learning") + geom_smooth(method = "lm")
p12 <- ggplot(learning2014, aes(x = Age, y = Points, col=gender))
p12 + geom_point() + ggtitle("Relationship between age and exam points") + geom_smooth(method = "lm")
p13 <- ggplot(learning2014, aes(x = Age, y = Attitude, col=gender))
p13 + geom_point() + ggtitle("Relationship between age and attitudes") + geom_smooth(method = "lm")
library(GGally)
pairs(learning2014[-1], col = learning2014$gender)
p <- ggpairs(learning2014, mapping = aes(col=gender, alpha = 0.3), lower = list(combo = wrap("facethist", bins = 20)))
# draw the plot
p
Summary of the variables
summary(learning2014)
## gender Age Attitude deep stra
## F:110 Min. :17.00 Min. :14.00 Min. :1.583 Min. :1.250
## M: 56 1st Qu.:21.00 1st Qu.:26.00 1st Qu.:3.333 1st Qu.:2.625
## Median :22.00 Median :32.00 Median :3.667 Median :3.188
## Mean :25.51 Mean :31.43 Mean :3.680 Mean :3.121
## 3rd Qu.:27.00 3rd Qu.:37.00 3rd Qu.:4.083 3rd Qu.:3.625
## Max. :55.00 Max. :50.00 Max. :4.917 Max. :5.000
## surf Points
## Min. :1.583 Min. : 7.00
## 1st Qu.:2.417 1st Qu.:19.00
## Median :2.833 Median :23.00
## Mean :2.787 Mean :22.72
## 3rd Qu.:3.167 3rd Qu.:27.75
## Max. :4.333 Max. :33.00
# another way of summarising the variables
#library(dplyr)
#learning2014 %>%
# group_by(gender) %>%
# summarise(mean = mean(Attitude), n = n())
The sample consist of mainly female participants. The majority of participants are between 20 to 30 years old. The variables are mostly normally distributed. The attitudes predict the exam points, but the learning strategies do not explain the exam points. Age does not explain the exam points or attitudes.
Fitting of a regression model to study whether attitudes, strategic and surface learning strategies explain the exam points. The learning strategies (strategic and surface) did not explain the exam points significantly. The exam points were significantly (p = 4.12e-09) explained by attitudes
# fit a linear model
my_model1 <- lm(Points ~ Attitude + stra + surf, data = learning2014) # how to use three explanatory vars
summary(my_model1)
##
## Call:
## lm(formula = Points ~ Attitude + stra + surf, data = learning2014)
##
## Residuals:
## Min 1Q Median 3Q Max
## -17.1550 -3.4346 0.5156 3.6401 10.8952
##
## Coefficients:
## Estimate Std. Error t value Pr(>|t|)
## (Intercept) 11.01711 3.68375 2.991 0.00322 **
## Attitude 0.33952 0.05741 5.913 1.93e-08 ***
## stra 0.85313 0.54159 1.575 0.11716
## surf -0.58607 0.80138 -0.731 0.46563
## ---
## Signif. codes: 0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
##
## Residual standard error: 5.296 on 162 degrees of freedom
## Multiple R-squared: 0.2074, Adjusted R-squared: 0.1927
## F-statistic: 14.13 on 3 and 162 DF, p-value: 3.156e-08
my_model2 <- lm(Points ~ Attitude, data = learning2014)
summary(my_model2)
##
## Call:
## lm(formula = Points ~ Attitude, data = learning2014)
##
## Residuals:
## Min 1Q Median 3Q Max
## -16.9763 -3.2119 0.4339 4.1534 10.6645
##
## Coefficients:
## Estimate Std. Error t value Pr(>|t|)
## (Intercept) 11.63715 1.83035 6.358 1.95e-09 ***
## Attitude 0.35255 0.05674 6.214 4.12e-09 ***
## ---
## Signif. codes: 0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
##
## Residual standard error: 5.32 on 164 degrees of freedom
## Multiple R-squared: 0.1906, Adjusted R-squared: 0.1856
## F-statistic: 38.61 on 1 and 164 DF, p-value: 4.119e-09
Produce the diagnostic plots: Residuals vs Fitted values, Normal QQ-plot and Residuals vs Leverage
plot(my_model2)
Read and explore the data
rm(list = ls()) # clear workspace
alc <- read.csv("~/Documents/GitHub/IODS-project/data/alc.csv") # my own data wrangling
variable.names(alc)
## [1] "school" "sex" "age" "address" "famsize"
## [6] "Pstatus" "Medu" "Fedu" "Mjob" "Fjob"
## [11] "reason" "nursery" "internet" "guardian" "traveltime"
## [16] "studytime" "failures" "schoolsup" "famsup" "paid"
## [21] "activities" "higher" "romantic" "famrel" "freetime"
## [26] "goout" "Dalc" "Walc" "health" "absences"
## [31] "G1" "G2" "G3" "alc_use" "high_use"
This data describes student performance in two Portuguese schools. The data attributes include school, student grades, demographic, social and school related features) and it was collected by using school reports and questionnaires. The data were combined from two datasets: (1) performance in mathematics and (2) portuguese language. The grades are means of Math and Portuguese: G1 - first period grade (numeric: from 0 to 20) G2 - second period grade (numeric: from 0 to 20) G3 - final grade (numeric: from 0 to 20, output target)
# access the tidyverse libraries tidyr, dplyr, ggplot2
library(tidyr); library(dplyr); library(ggplot2)
##
## Attaching package: 'dplyr'
## The following object is masked from 'package:GGally':
##
## nasa
## The following objects are masked from 'package:stats':
##
## filter, lag
## The following objects are masked from 'package:base':
##
## intersect, setdiff, setequal, union
chosen_vars <- c("high_use","G3","absences","health","studytime") # choose relevant vars
chosen_data <- select(alc, one_of(chosen_vars))
#chosen_data$high_useN <- as.numeric(chosen_data$high_use)
gather(chosen_data) %>% glimpse
## Observations: 1,910
## Variables: 2
## $ key <chr> "high_use", "high_use", "high_use", "high_use", "high_us...
## $ value <int> 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1,...
gather(chosen_data) %>% ggplot(aes(value)) + facet_wrap("key", scales = "free") + geom_bar() # bar plots
# box plots
ggplot(chosen_data, aes(x=high_use, y = G3)) + geom_boxplot()
ggplot(chosen_data, aes(x=high_use, y = absences)) + geom_boxplot()
ggplot(chosen_data, aes(x=high_use, y = health)) + geom_boxplot()
ggplot(chosen_data, aes(x=high_use, y = studytime)) + geom_boxplot()
Distibutions:
The effect of alcohol consumption on the selected variables:
m <- glm(high_use ~ G3 + absences + health + studytime, data = chosen_data, family = "binomial") # find the model with glm()
summary(m) # summary of the model
##
## Call:
## glm(formula = high_use ~ G3 + absences + health + studytime,
## family = "binomial", data = chosen_data)
##
## Deviance Residuals:
## Min 1Q Median 3Q Max
## -2.2434 -0.8399 -0.6601 1.1619 2.1430
##
## Coefficients:
## Estimate Std. Error z value Pr(>|z|)
## (Intercept) 0.11336 0.61876 0.183 0.854635
## G3 -0.05307 0.03602 -1.473 0.140698
## absences 0.07837 0.02274 3.446 0.000569 ***
## health 0.06701 0.08551 0.784 0.433240
## studytime -0.50608 0.15731 -3.217 0.001295 **
## ---
## Signif. codes: 0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
##
## (Dispersion parameter for binomial family taken to be 1)
##
## Null deviance: 465.68 on 381 degrees of freedom
## Residual deviance: 430.62 on 377 degrees of freedom
## AIC: 440.62
##
## Number of Fisher Scoring iterations: 4
OddsRatios <- coef(m) %>% exp
ConfInt <- confint(m) %>% exp
## Waiting for profiling to be done...
cbind(OddsRatios, ConfInt)
## OddsRatios 2.5 % 97.5 %
## (Intercept) 1.1200365 0.3308837 3.7712228
## G3 0.9483123 0.8833403 1.0177770
## absences 1.0815248 1.0366149 1.1334569
## health 1.0693034 0.9055302 1.2671462
## studytime 0.6028539 0.4387386 0.8140308
Interpretation of the results:
m2 <- glm(high_use ~ absences + studytime, data = chosen_data, family = "binomial") # find the model with glm()
summary(m2)
##
## Call:
## glm(formula = high_use ~ absences + studytime, family = "binomial",
## data = chosen_data)
##
## Deviance Residuals:
## Min 1Q Median 3Q Max
## -2.2128 -0.8387 -0.7046 1.1996 2.1832
##
## Coefficients:
## Estimate Std. Error z value Pr(>|z|)
## (Intercept) -0.16640 0.33954 -0.490 0.624087
## absences 0.08054 0.02285 3.524 0.000425 ***
## studytime -0.55015 0.15550 -3.538 0.000403 ***
## ---
## Signif. codes: 0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
##
## (Dispersion parameter for binomial family taken to be 1)
##
## Null deviance: 465.68 on 381 degrees of freedom
## Residual deviance: 433.65 on 379 degrees of freedom
## AIC: 439.65
##
## Number of Fisher Scoring iterations: 4
# predict() the probability of high_use
probabilities <- predict(m2, type = "response")
# add the predicted probabilities to 'chosen_data'
chosen_data <- mutate(chosen_data, probability = probabilities)
chosen_data <- mutate(chosen_data, prediction = probability > 0.5)
# 2x2 cross tabulation of predictions versus the actual values
t <- table(high_use = chosen_data$high_use, prediction = chosen_data$prediction)
t
## prediction
## high_use FALSE TRUE
## FALSE 256 12
## TRUE 96 18
# The total proportion of inaccurately classified individuals (= the training error)
NumErr = t[2,1] + t[1,2]
Tot = 382 # num obs
PropErr = round(NumErr / Tot, 2)
Accuracy = 100 - (PropErr*100)
The model has high predictive power. In total, the model achieved an accurcay of 72% in correct classification of individuals to high/low alcohol consumers based on their school absences and study time. This much better than guessing which would give an accuracy of 50%.
rm(list = ls()) # clear workspace
library(MASS)
##
## Attaching package: 'MASS'
## The following object is masked from 'package:dplyr':
##
## select
data("Boston")
str(Boston)
## 'data.frame': 506 obs. of 14 variables:
## $ crim : num 0.00632 0.02731 0.02729 0.03237 0.06905 ...
## $ zn : num 18 0 0 0 0 0 12.5 12.5 12.5 12.5 ...
## $ indus : num 2.31 7.07 7.07 2.18 2.18 2.18 7.87 7.87 7.87 7.87 ...
## $ chas : int 0 0 0 0 0 0 0 0 0 0 ...
## $ nox : num 0.538 0.469 0.469 0.458 0.458 0.458 0.524 0.524 0.524 0.524 ...
## $ rm : num 6.58 6.42 7.18 7 7.15 ...
## $ age : num 65.2 78.9 61.1 45.8 54.2 58.7 66.6 96.1 100 85.9 ...
## $ dis : num 4.09 4.97 4.97 6.06 6.06 ...
## $ rad : int 1 2 2 3 3 3 5 5 5 5 ...
## $ tax : num 296 242 242 222 222 222 311 311 311 311 ...
## $ ptratio: num 15.3 17.8 17.8 18.7 18.7 18.7 15.2 15.2 15.2 15.2 ...
## $ black : num 397 397 393 395 397 ...
## $ lstat : num 4.98 9.14 4.03 2.94 5.33 ...
## $ medv : num 24 21.6 34.7 33.4 36.2 28.7 22.9 27.1 16.5 18.9 ...
This data has 506 osbervations (rows) and 14 variables (columns). The data includes information about housing values of suburbs of Boston, such as crime rate, business, accessibility to highways, and characteristics of the citizens in the area.
gather(Boston) %>% glimpse
## Observations: 7,084
## Variables: 2
## $ key <chr> "crim", "crim", "crim", "crim", "crim", "crim", "crim", ...
## $ value <dbl> 0.00632, 0.02731, 0.02729, 0.03237, 0.06905, 0.02985, 0....
gather(Boston) %>% ggplot(aes(value)) + facet_wrap("key", scales = "free") + geom_histogram() # bar plots
## `stat_bin()` using `bins = 30`. Pick better value with `binwidth`.
summary(Boston)
## crim zn indus chas
## Min. : 0.00632 Min. : 0.00 Min. : 0.46 Min. :0.00000
## 1st Qu.: 0.08204 1st Qu.: 0.00 1st Qu.: 5.19 1st Qu.:0.00000
## Median : 0.25651 Median : 0.00 Median : 9.69 Median :0.00000
## Mean : 3.61352 Mean : 11.36 Mean :11.14 Mean :0.06917
## 3rd Qu.: 3.67708 3rd Qu.: 12.50 3rd Qu.:18.10 3rd Qu.:0.00000
## Max. :88.97620 Max. :100.00 Max. :27.74 Max. :1.00000
## nox rm age dis
## Min. :0.3850 Min. :3.561 Min. : 2.90 Min. : 1.130
## 1st Qu.:0.4490 1st Qu.:5.886 1st Qu.: 45.02 1st Qu.: 2.100
## Median :0.5380 Median :6.208 Median : 77.50 Median : 3.207
## Mean :0.5547 Mean :6.285 Mean : 68.57 Mean : 3.795
## 3rd Qu.:0.6240 3rd Qu.:6.623 3rd Qu.: 94.08 3rd Qu.: 5.188
## Max. :0.8710 Max. :8.780 Max. :100.00 Max. :12.127
## rad tax ptratio black
## Min. : 1.000 Min. :187.0 Min. :12.60 Min. : 0.32
## 1st Qu.: 4.000 1st Qu.:279.0 1st Qu.:17.40 1st Qu.:375.38
## Median : 5.000 Median :330.0 Median :19.05 Median :391.44
## Mean : 9.549 Mean :408.2 Mean :18.46 Mean :356.67
## 3rd Qu.:24.000 3rd Qu.:666.0 3rd Qu.:20.20 3rd Qu.:396.23
## Max. :24.000 Max. :711.0 Max. :22.00 Max. :396.90
## lstat medv
## Min. : 1.73 Min. : 5.00
## 1st Qu.: 6.95 1st Qu.:17.02
## Median :11.36 Median :21.20
## Mean :12.65 Mean :22.53
## 3rd Qu.:16.95 3rd Qu.:25.00
## Max. :37.97 Max. :50.00
cor_matrix <-cor(Boston)
cor_matrix <-round(cor_matrix, digits=2)
cor_matrix
## crim zn indus chas nox rm age dis rad tax
## crim 1.00 -0.20 0.41 -0.06 0.42 -0.22 0.35 -0.38 0.63 0.58
## zn -0.20 1.00 -0.53 -0.04 -0.52 0.31 -0.57 0.66 -0.31 -0.31
## indus 0.41 -0.53 1.00 0.06 0.76 -0.39 0.64 -0.71 0.60 0.72
## chas -0.06 -0.04 0.06 1.00 0.09 0.09 0.09 -0.10 -0.01 -0.04
## nox 0.42 -0.52 0.76 0.09 1.00 -0.30 0.73 -0.77 0.61 0.67
## rm -0.22 0.31 -0.39 0.09 -0.30 1.00 -0.24 0.21 -0.21 -0.29
## age 0.35 -0.57 0.64 0.09 0.73 -0.24 1.00 -0.75 0.46 0.51
## dis -0.38 0.66 -0.71 -0.10 -0.77 0.21 -0.75 1.00 -0.49 -0.53
## rad 0.63 -0.31 0.60 -0.01 0.61 -0.21 0.46 -0.49 1.00 0.91
## tax 0.58 -0.31 0.72 -0.04 0.67 -0.29 0.51 -0.53 0.91 1.00
## ptratio 0.29 -0.39 0.38 -0.12 0.19 -0.36 0.26 -0.23 0.46 0.46
## black -0.39 0.18 -0.36 0.05 -0.38 0.13 -0.27 0.29 -0.44 -0.44
## lstat 0.46 -0.41 0.60 -0.05 0.59 -0.61 0.60 -0.50 0.49 0.54
## medv -0.39 0.36 -0.48 0.18 -0.43 0.70 -0.38 0.25 -0.38 -0.47
## ptratio black lstat medv
## crim 0.29 -0.39 0.46 -0.39
## zn -0.39 0.18 -0.41 0.36
## indus 0.38 -0.36 0.60 -0.48
## chas -0.12 0.05 -0.05 0.18
## nox 0.19 -0.38 0.59 -0.43
## rm -0.36 0.13 -0.61 0.70
## age 0.26 -0.27 0.60 -0.38
## dis -0.23 0.29 -0.50 0.25
## rad 0.46 -0.44 0.49 -0.38
## tax 0.46 -0.44 0.54 -0.47
## ptratio 1.00 -0.18 0.37 -0.51
## black -0.18 1.00 -0.37 0.33
## lstat 0.37 -0.37 1.00 -0.74
## medv -0.51 0.33 -0.74 1.00
corrplot(cor_matrix, method = "color")
Overall, the variables show strong correlations with each other, therefore only the strongest (> 0.7 or < -0.7) are interpreted below
‘indus’ correlates positively with ‘nox’ (0.76) and ‘tax’ (0.72) and negatively with ‘dis’ (-0.71), suggesting that the proportion of non-retail business acres is associated with higher nitrogen oxides concentration and tax rate and with shorter distances from Boston employment centres.
‘rm’ correlates positively with ‘medv’ (0.7), suggesting that the average number of rooms is associated with higher median of owner-occupied homes in $1000s.
‘age’ correlates negatively with ‘dis’ (-0.75), suggesting that the proportion of units built prior to 1940 is associated with shorter distance from employment centres.
‘rad’ correlates with ‘tax’ (0.91): accessibility to highways is highly correlated with tax rate.
‘lstat’ correlates negatively with ‘medv’ (-0.74): the percentage of lower status population (is this appropriate??) is associated with lower amount of owner-occupied homes in $1000s.
boston_scaled <- scale(Boston)
summary(boston_scaled)
## crim zn indus
## Min. :-0.419367 Min. :-0.48724 Min. :-1.5563
## 1st Qu.:-0.410563 1st Qu.:-0.48724 1st Qu.:-0.8668
## Median :-0.390280 Median :-0.48724 Median :-0.2109
## Mean : 0.000000 Mean : 0.00000 Mean : 0.0000
## 3rd Qu.: 0.007389 3rd Qu.: 0.04872 3rd Qu.: 1.0150
## Max. : 9.924110 Max. : 3.80047 Max. : 2.4202
## chas nox rm age
## Min. :-0.2723 Min. :-1.4644 Min. :-3.8764 Min. :-2.3331
## 1st Qu.:-0.2723 1st Qu.:-0.9121 1st Qu.:-0.5681 1st Qu.:-0.8366
## Median :-0.2723 Median :-0.1441 Median :-0.1084 Median : 0.3171
## Mean : 0.0000 Mean : 0.0000 Mean : 0.0000 Mean : 0.0000
## 3rd Qu.:-0.2723 3rd Qu.: 0.5981 3rd Qu.: 0.4823 3rd Qu.: 0.9059
## Max. : 3.6648 Max. : 2.7296 Max. : 3.5515 Max. : 1.1164
## dis rad tax ptratio
## Min. :-1.2658 Min. :-0.9819 Min. :-1.3127 Min. :-2.7047
## 1st Qu.:-0.8049 1st Qu.:-0.6373 1st Qu.:-0.7668 1st Qu.:-0.4876
## Median :-0.2790 Median :-0.5225 Median :-0.4642 Median : 0.2746
## Mean : 0.0000 Mean : 0.0000 Mean : 0.0000 Mean : 0.0000
## 3rd Qu.: 0.6617 3rd Qu.: 1.6596 3rd Qu.: 1.5294 3rd Qu.: 0.8058
## Max. : 3.9566 Max. : 1.6596 Max. : 1.7964 Max. : 1.6372
## black lstat medv
## Min. :-3.9033 Min. :-1.5296 Min. :-1.9063
## 1st Qu.: 0.2049 1st Qu.:-0.7986 1st Qu.:-0.5989
## Median : 0.3808 Median :-0.1811 Median :-0.1449
## Mean : 0.0000 Mean : 0.0000 Mean : 0.0000
## 3rd Qu.: 0.4332 3rd Qu.: 0.6024 3rd Qu.: 0.2683
## Max. : 0.4406 Max. : 3.5453 Max. : 2.9865
The data is now standardized to zero mean.
boston_scaled <- as.data.frame(boston_scaled)
bins <- quantile(boston_scaled$crim) # create a quantile vector of crim and print it
# create a categorical variable 'crime'
crime <- cut(boston_scaled$crim, breaks = bins, include.lowest = TRUE, label = c("low", "med_low", "med_high", "high"))
table(crime) # print the table
## crime
## low med_low med_high high
## 127 126 126 127
boston_scaled <- cbind(boston_scaled, crime) # bind crime to boston_scaled
boston_scaled <- dplyr::select(boston_scaled, -crim) # remove original crim from the dataset
n <- nrow(boston_scaled) # number of rows
ind <- sample(n, size = n * 0.8) # choose randomly 80% of the rows
train <- boston_scaled[ind,] # create the train set
test <- boston_scaled[-ind,] # create the test set
lda.fit <- lda(crime ~., data = train) # crime rate is the target variable and all the other variables are predictors
lda.fit # print the solution
## Call:
## lda(crime ~ ., data = train)
##
## Prior probabilities of groups:
## low med_low med_high high
## 0.2623762 0.2524752 0.2475248 0.2376238
##
## Group means:
## zn indus chas nox rm
## low 0.95945867 -0.8736810 -0.123759247 -0.8608359 0.4715759
## med_low -0.08137866 -0.2445444 -0.002135914 -0.5760720 -0.1233722
## med_high -0.38261997 0.1435672 0.239493963 0.3054509 0.2108483
## high -0.48724019 1.0172418 -0.108283225 1.0174409 -0.3976487
## age dis rad tax ptratio
## low -0.8393850 0.8103087 -0.6839198 -0.7576931 -0.44223764
## med_low -0.3631045 0.3797533 -0.5495071 -0.4572909 -0.04240666
## med_high 0.3826833 -0.3195191 -0.3800745 -0.3092325 -0.28847543
## high 0.7706830 -0.8292402 1.6368728 1.5131579 0.77931510
## black lstat medv
## low 0.3809885 -0.76048984 0.561007732
## med_low 0.3114052 -0.13188358 -0.004846203
## med_high 0.1088360 -0.07204296 0.263799741
## high -0.8592553 0.86339861 -0.722996383
##
## Coefficients of linear discriminants:
## LD1 LD2 LD3
## zn 0.08238760 0.84587350 -0.83645794
## indus 0.00447987 -0.17532951 0.28064174
## chas -0.08432467 -0.10650700 0.07333207
## nox 0.40629109 -0.71536542 -1.30313753
## rm -0.11596422 -0.06941634 -0.14668263
## age 0.25580500 -0.32138650 -0.25265126
## dis -0.04862418 -0.46286056 0.17841191
## rad 2.99045701 0.95066999 -0.26396363
## tax -0.01498848 -0.21052792 0.73536274
## ptratio 0.08595505 0.05934535 -0.21134140
## black -0.15467486 0.00223080 0.08973001
## lstat 0.23255642 -0.23753552 0.42215818
## medv 0.19459575 -0.44943279 -0.21178783
##
## Proportion of trace:
## LD1 LD2 LD3
## 0.9457 0.0384 0.0159
classes <- as.numeric(train$crime) # target classes as numeric
plot(lda.fit, dimen = 2, col = classes, pch = classes) # plot the lda results
correct_classes <- test$crime # save the crime categories from the test set
test <- dplyr::select(test, -crime) # remove crime from the test dataset
lda.pred <- predict(lda.fit, newdata = test) # predict classes with test data
table(correct = correct_classes, predicted = lda.pred$class) # Cross tabulate the results
## predicted
## correct low med_low med_high high
## low 15 6 0 0
## med_low 4 18 2 0
## med_high 0 6 20 0
## high 0 0 0 31
Overall, the model performs well in predicting the crime categories. The high crime category is predicted fully, medium high is predicted well execpt small confusion with medium low crime rate category. Low and med_low categories are mixed.
### Reload and normalize Boston dataset and calculate the euclidean distances between the observations
library(MASS)
data('Boston')
boston_scaled <- scale(Boston)
boston_scaled <- as.data.frame(boston_scaled)
dist_eu <- dist(boston_scaled) #Calculate the distances
k_max <- 25 # determine the maximum number of clusters
twcss <- sapply(1:k_max, function(k){kmeans(boston_scaled, k)$tot.withinss}) # calculate the total within sum of squares
qplot(x = 1:k_max, y = twcss, geom = 'line') # visualize the results
km <-kmeans(boston_scaled, centers = 5) # k-means clustering
pairs(boston_scaled, col = km$cluster) # plot the clusters
Five seems to be an optimal number of clusters, because a drop in the sum of squared distances around there.
library(MASS)
data('Boston')
boston_scaled <- scale(Boston)
boston_scaled <- as.data.frame(boston_scaled)
# Perform k-means on the original Boston data with some reasonable number of clusters (> 2)
km_4 <-kmeans(boston_scaled, centers = 4) # k-means clustering
clusters <- as.numeric(km_4$cluster)
lda.fit4 <- lda(clusters ~., data = boston_scaled) # perform LDA using the clusters
lda.fit4
## Call:
## lda(clusters ~ ., data = boston_scaled)
##
## Prior probabilities of groups:
## 1 2 3 4
## 0.3478261 0.1996047 0.1916996 0.2608696
##
## Group means:
## crim zn indus chas nox rm
## 1 -0.3955833 -0.2254704 -0.5890095 -0.11573985 -0.6008751 -0.06953428
## 2 -0.3961410 1.4923250 -1.0073590 0.03952046 -0.8201975 1.14916783
## 3 -0.3166884 -0.4817148 0.7363879 0.21473488 0.5617886 -0.56201562
## 4 1.0632703 -0.4872402 1.0149946 -0.03371693 1.0159127 -0.37357880
## age dis rad tax ptratio black
## 1 -0.4918015 0.4322643 -0.5792552 -0.6830752 -0.01226651 0.36362199
## 2 -0.9067300 0.9150799 -0.5986698 -0.6556098 -1.01943385 0.35076234
## 3 0.8101020 -0.6166607 -0.5840517 -0.1592236 -0.01279411 -0.00268091
## 4 0.7542188 -0.8233749 1.6596029 1.5294129 0.80577843 -0.75124560
## lstat medv
## 1 -0.4012240 0.07402657
## 2 -0.9782213 1.20570299
## 3 0.6131707 -0.48287523
## 4 0.8328654 -0.66640742
##
## Coefficients of linear discriminants:
## LD1 LD2 LD3
## crim 0.08139384 -0.22359028 0.06554147
## zn 0.33554601 -0.88266028 -1.21807881
## indus 0.33981045 0.59239693 -0.66723420
## chas -0.01718605 0.12636697 -0.09003424
## nox -0.01896734 -0.03907779 -0.36248494
## rm -0.06514429 -0.54171225 -0.27478691
## age 0.04189907 0.47483313 -0.49074354
## dis -0.22488672 -0.10703816 0.20753920
## rad 5.99985509 -1.25972869 1.35203394
## tax 0.22488689 0.01764947 -0.74090656
## ptratio 0.25626572 0.24911107 -0.03140773
## black -0.04205519 -0.04273764 0.09403661
## lstat 0.02170577 -0.15538625 -0.50478462
## medv -0.11487427 -0.61561036 -0.39927321
##
## Proportion of trace:
## LD1 LD2 LD3
## 0.9131 0.0678 0.0191
# the function to draw lda biplot arrows
my_scale = 10 # unable to draw the arrows - i'm not sure what myscale does -tested with different values without any effect
lda.arrows <- function(x, myscale = my_scale, arrow_heads = 0.1, color = "black", tex = 0.75, choices = c(1,2)){
heads <- coef(x)
arrows(x0 = 0, y0 = 0,
x1 = myscale * heads[,choices[1]],
y1 = myscale * heads[,choices[2]], col=color, length = arrow_heads)
text(myscale * heads[,choices], labels = row.names(heads),
cex = tex, col=color, pos=3)
}
plot(lda.fit4, dimen = 3, col = clusters, pch = clusters)
lda.arrows(lda.fit4, myscale = my_scale)